package org.liaohailong.hellovideocache;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.util.Log;
import android.Manifest;
import android.widget.TextView;

import org.liaohailong.hellovideocache.databinding.ActivityMainBinding;
import org.liaohailong.library.HelloVideoCache;
import org.liaohailong.library.HelloVideoCacheConfig;
import org.liaohailong.library.util.IpUtil;
import org.liaohailong.library.util.PermissionUtil;

import java.io.File;

public class MainActivity extends AppCompatActivity {
    private void log(@NonNull String format, Object... args) {
        String msg = String.format(format, args);
        Log.i("Victor", msg);
    }

    private ActivityMainBinding binding;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        binding = ActivityMainBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());

        // 音视频采集相关权限
        String[] permissions = new String[]{
                Manifest.permission.ACCESS_WIFI_STATE,
                Manifest.permission.ACCESS_FINE_LOCATION,
        };
        if (PermissionUtil.requestIfNeed(this, permissions, 0)) {
            return;
        }

        String ip = IpUtil.getLocalIpAddress(this);
        File videoCacheDir = getExternalFilesDir("hellovideocache");
        assert videoCacheDir != null;
        if (!videoCacheDir.exists()) {
            if (!videoCacheDir.mkdirs()) {
                log("cannot mkdirs %s", videoCacheDir.getAbsolutePath());
            }
        }


        final HelloVideoCache helloVideoCache = new HelloVideoCache();
        // Example of a call to a native method
        TextView tv = binding.sampleText;
        tv.setText("ip: " + ip);
        tv.setOnClickListener(v -> {

            HelloVideoCacheConfig config = new HelloVideoCacheConfig();
            config.defaultPort = 8898; // 绑定端口
            config.cacheDir = videoCacheDir.getAbsolutePath(); // 缓存根目录
            // TODO: 测试代码，缓存全清
            if (FileUtils.deleteDirectory(new File(config.cacheDir))) {
                log("delete: %s", config.cacheDir);
            }
            helloVideoCache.setConfig(config);
            helloVideoCache.start();

        });
        tv.post(tv::performClick);
    }

}